<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>00p4(原型-实现each方法)</title>
</head>
<body>
<script type="text/javascript">
	
	// Array each 方法

	//ECMA5 forEach方法只适合遍历一维数组
	/*
	var arr = [1,2,3,4,5];

	arr.forEach(function (item, index, array) {
		alert(item);
	})
	*/

	//自定义实现Array each方法(可遍历多维数组)

	var arr = [1,2,3,[4,[5,[6]]]];

	Array.prototype.each = function (fn) {
		try{
			this.i || (this.i = 0);
			if(this.length > 0 && fn.constructor == Function){
				while(this.i < this.length){
					var e = this[this.i];
					if(e && e.constructor == Array){
						e.each(fn);
					} else {
						fn.call(e,e);
					}
					this.i++;
				}
			}
			this.i = null;
		} catch (e) {
			throw new Error('');
		}
		return this;
	}

	arr.each(function (item, index, array) {
		alert(item);
	})

</script>
</body>
</html>